package com.landeb.shop.huo.act;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.tv.TvContentRating;
import android.os.Bundle;
import android.support.v7.widget.SwitchCompat;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.landeb.shop.R;
import com.landeb.shop.huo.ActControler;
import com.landeb.shop.huo.MyApplication;
import com.landeb.shop.huo.bean.BeanUserData;
import com.landeb.shop.huo.httpRequest.UserConfirmationRequest;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


public class LoginActivity extends BaseActivity implements View.OnClickListener {

    private Button btnLogin, btnSignUp, btnGetPassword;
    private LinearLayout btnBack;

    private EditText etAccount, etPassword;
    private SwitchCompat mSwitchPassword;
    private LinearLayout qqLogin, weiChatLogin;

    private String mUrl;
    private OkHttpClient mClient;
    private Retrofit mRetrofit;
    private UserConfirmationRequest mUserConfirmationRequest;

    private CheckBox mCbLoginWay;
    private TextView mTvForgetPassword;
    private LinearLayout mPasswordContainer, mSmscodeContainer;
    private EditText mEtSmscode;
    private ImageView mIvClearSmscode;
    private Button mBtnGetSmscode;


    public static void toAct(Context context) {
        Intent intent = new Intent(context, LoginActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

//        SharedPreferences preferences = getSharedPreferences("user", Context.MODE_PRIVATE);
//        String s = preferences.getString("token", "null");
//        Toast.makeText(this,s,Toast.LENGTH_SHORT).show();


        mClient = MyApplication.getClient();
        mUrl = MyApplication.BASE_URL;
        mRetrofit = new Retrofit.Builder()
                .baseUrl(mUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(mClient)
                .build();
        mUserConfirmationRequest = mRetrofit.create(UserConfirmationRequest.class);


        initView();
        initData();
        initEvent();

    }

    private void initEvent() {

        btnBack.setOnClickListener(this);
        btnLogin.setOnClickListener(this);
        btnSignUp.setOnClickListener(this);
        btnGetPassword.setOnClickListener(this);


        mSwitchPassword.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

                if (b) {
                    etPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    etPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }

            }
        });

        qqLogin.setOnClickListener(this);
        weiChatLogin.setOnClickListener(this);

        mCbLoginWay.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                if (!isChecked) {
                    mPasswordContainer.setVisibility(View.VISIBLE);
                    mSmscodeContainer.setVisibility(View.GONE);
                } else {
                    mPasswordContainer.setVisibility(View.GONE);
                    mSmscodeContainer.setVisibility(View.VISIBLE);
                }

            }
        });

        mCbLoginWay.setChecked(false);

        mTvForgetPassword.setOnClickListener(this);
        mIvClearSmscode.setOnClickListener(this);
        mBtnGetSmscode.setOnClickListener(this);
    }

    private void initData() {

    }

    private void initView() {

        btnBack = (LinearLayout) findViewById(R.id.act_login_btn_back);
        btnLogin = (Button) findViewById(R.id.act_login_btn_login);
        btnSignUp = (Button) findViewById(R.id.act_login_btn_signUp);
        btnGetPassword = (Button) findViewById(R.id.act_login_btn_getPassword);

        etAccount = (EditText) findViewById(R.id.act_login_edit_account);
        etPassword = (EditText) findViewById(R.id.act_login_edit_password);
        mSwitchPassword = (SwitchCompat) findViewById(R.id.act_login_switch_password);

        qqLogin = (LinearLayout) findViewById(R.id.act_login_ll_qq_login);
        weiChatLogin = (LinearLayout) findViewById(R.id.act_login_ll_weiXin_login);

        mCbLoginWay = (CheckBox) findViewById(R.id.act_login_cb_loginWay);
        mTvForgetPassword = (TextView) findViewById(R.id.act_login_tv_forgetPassWord);
        mPasswordContainer = (LinearLayout) findViewById(R.id.act_login_ll_password_container);
        mSmscodeContainer = (LinearLayout) findViewById(R.id.act_login_ll_smscode_container);
        mIvClearSmscode = (ImageView) findViewById(R.id.act_login_iv_clearSmscode);
        mEtSmscode = (EditText) findViewById(R.id.act_login_edit_smscode);
        mBtnGetSmscode = (Button) findViewById(R.id.act_login_btn_getSmscode);

    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.act_login_btn_back:
                // TODO: 2016/10/27 返回按钮
                onBackPressed();
                break;
            case R.id.act_login_btn_login:
                // TODO: 2016/10/27 登陆逻辑

                if (mCbLoginWay.isChecked()) {
                    if (TextUtils.isEmpty(mEtSmscode.getText().toString())) {
                        Toast.makeText(this,"请输入短信验证码",Toast.LENGTH_SHORT).show();
                        return;
                    }
                }else {
                    if (TextUtils.isEmpty(etPassword.getText().toString())) {
                        Toast.makeText(this,"请输入密码",Toast.LENGTH_SHORT).show();
                        return;
                    }
                }

                final ProgressDialog dialog = new ProgressDialog(this, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
                dialog.setCancelable(true);
                dialog.setMessage("正在登陆");
                dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                dialog.show();

                mUserConfirmationRequest.login(etAccount.getText().toString(),mCbLoginWay.isChecked()?mEtSmscode.getText().toString():etPassword.getText().toString(),mCbLoginWay.isChecked()?"sms":"password")
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Subscriber<BeanUserData>() {
                            @Override
                            public void onCompleted() {
                                Log.e("login", "successed");
                                dialog.dismiss();
                            }

                            @Override
                            public void onError(Throwable e) {
                                Log.e("login", "ERROR    " + e.toString());
                                dialog.dismiss();
                            }

                            @Override
                            public void onNext(BeanUserData beanUserData) {

                                if (beanUserData.getStatus() == 1) {

                                    SharedPreferences preferences = getSharedPreferences("user", Context.MODE_PRIVATE);
                                    SharedPreferences.Editor editor = preferences.edit();
                                    editor.putString("token", beanUserData.getData().getToken());
                                    editor.commit();


                                    MyApplication.resetClient(beanUserData.getData().getToken());
                                    ActControler.removeAllAct();

                                    MainActivity.toAct(LoginActivity.this);

                                } else if (beanUserData.getStatus() == 0) {
                                    Toast.makeText(LoginActivity.this, beanUserData.getInfo(), Toast.LENGTH_SHORT).show();
                                }


                            }
                        });

                break;
            case R.id.act_login_btn_signUp:
                // TODO: 2016/10/27 注册按钮
                SignUpActivity.toAct(this);
                break;
            case R.id.act_login_btn_getPassword:

                break;
            case R.id.act_login_ll_qq_login:
                // TODO: 2016/10/27 qq登陆
                break;
            case R.id.act_login_ll_weiXin_login:
                // TODO: 2016/10/27 微信登陆
                break;
            case R.id.act_login_tv_forgetPassWord:
                // TODO: 2016/10/27 找回密码
                PasswordFindActivity.toAct(this);
                break;
            case R.id.act_login_btn_getSmscode:
                // TODO: 2017/8/23 获取验证码

                if (TextUtils.isEmpty(etAccount.getText().toString())){
                    Toast.makeText(this,"请输入手机号",Toast.LENGTH_SHORT).show();
                    return;
                }

                mUserConfirmationRequest.sendSmsCode(etAccount.getText().toString())
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Subscriber<BeanUserData>() {
                            @Override
                            public void onCompleted() {

                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onNext(BeanUserData beanUserData) {
                                Toast.makeText(LoginActivity.this, beanUserData.getStatus() + beanUserData.getInfo(), Toast.LENGTH_SHORT).show();

                            }
                        });
                break;
            case R.id.act_login_iv_clearSmscode:
                // TODO: 2017/8/23 清空验证码
                mEtSmscode.setText("");
                break;
        }

    }


}
